package cn.hwm.proxy.socketio.bio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端，接受数据（使用1.4版本bio实现）
 */
public class Server {

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(5050);

        while (true) {
            new Thread(new ServerHandler(serverSocket.accept())).start();
        }
    }

    static class ServerHandler implements Runnable {

        private Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try (
                    DataOutputStream dos = new DataOutputStream(this.socket.getOutputStream());
                    DataInputStream dis = new DataInputStream(this.socket.getInputStream())
            ) {

//                System.out.println("睡眠1秒");
//                Thread.sleep(1000);

                // 向客户端回复信息
                dos.writeUTF("服务端返回的数据");

                // 读取客户端数据
                System.out.println(dis.readUTF());
                System.out.println(dis.readUTF());

                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}